package com.example.sfm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sfm.exception.ObjectException;
import com.example.sfm.pojo.dto.FeedbackDto;
import com.example.sfm.pojo.dto.FeedbackQueryDto;
import com.example.sfm.pojo.dto.ReplyDto;
import com.example.sfm.pojo.entity.Feedback;
import com.example.sfm.mapper.FeedbackMapper;
import com.example.sfm.pojo.vo.FeedbackVo;
import com.example.sfm.result.PageResult;
import com.example.sfm.service.IFeedbackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sfm.service.IUsersService;
import com.example.sfm.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sfm
 * @since 2025-03-07
 */
@Service
@RequiredArgsConstructor
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements IFeedbackService {
    private final IUsersService usersService;

    /**
     * 创建反馈
     */
    @Override
    public void createFeedback(FeedbackDto dto) {
        Feedback entity = BeanUtil.copyProperties(dto, Feedback.class);
        entity.setUserId(ThreadLocalUtil.getId());
        if (!save(entity)) {
            throw new ObjectException("创建反馈失败！");
        }
    }

    /**
     * 分页查询
     */
    @Override
    public PageResult<?> listFeedbacks(@NotNull FeedbackQueryDto dto) {
        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<Feedback>()
                .eq(dto.getUserId() != null, Feedback::getUserId, dto.getUserId())
                .eq(dto.getStatus() != null, Feedback::getStatus, dto.getStatus())
                .orderByDesc(Feedback::getCreatedAt);

        Page<Feedback> page = page(new Page<>(dto.getPageNum(), dto.getPageSize()), wrapper);
        return new PageResult<>(page.getTotal(),
                page.getRecords().stream()
                        .map(f -> BeanUtil.copyProperties(f, FeedbackVo.class).setFullName(usersService.getById(f.getUserId()).getFullName()))
                        .toList());
    }

    /**
     * 更新基本信息
     */
    @Override
    public void updateFeedback(Integer id, FeedbackDto dto) {
        Feedback entity = getById(id);
        if (entity == null) throw new ObjectException("反馈不存在");

        // 仅允许更新留言内容
        entity.setMessage(dto.getMessage());
        if (!updateById(entity)) {
            throw new ObjectException("更新反馈失败");
        }
    }

    /**
     * 处理回复（包含事务管理）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleReply(Integer id, ReplyDto reply) {
        Feedback entity = getById(id);
        if (entity == null) throw new ObjectException("反馈不存在");

        entity.setReply(reply.getReply())
                .setStatus(1)
                .setRepliedAt(LocalDateTime.now());

        if (!updateById(entity)) {
            throw new ObjectException("回复处理失败");
        }
    }

    /**
     * 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFeedbacks(List<Integer> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ObjectException("ID列表不能为空");
        }
        if (!removeBatchByIds(ids.stream().distinct().toList())) {
            throw new ObjectException("删除反馈失败");
        }
    }
}
